<template>
    <div>
        <el-radio-group v-model="budgetType">
            <el-radio-button label="收入" :value="0"></el-radio-button>
            <el-radio-button label="支出" :value="1"></el-radio-button>
        </el-radio-group>
        <component :is="filterForm" :siftInfo="siftInfo" @filter-change="getSiftedData"></component>
        <!-- 新增和查询 -->
        <div class="options">
            <el-button icon="Plus" @click="openUpdateDialog(true)" style="margin-right: 20px;">新增</el-button>   
                <el-upload
                    ref="uploadRef"
                    class="upload-demo"
                    action="localhost:8081/test"
                    :http-request="postPic"
                    :limit="1"
                >
                    <template #trigger>
                    <el-button type="primary" icon="Plus">通过图片新增</el-button>
                    </template>
                </el-upload>
            <el-input prefix-icon="Search" style="width:200px;height:34px;margin-left:40px" id="search" placeholder="通过描述查询"
                @keyup.enter="searchItems" v-model="siftInfo.description"></el-input>
        </div>

        <modify-budget-table :budgetData="budgetData" :budgetType="budgetType" :total="total" 
        @page-change="getSiftedData" @modify-click="openModifyDialog" @delete-click="openDeleteDialog"/>
        <!-- 下面的dialog不方便和上面的filterform一样使用componentIs，由以下几个原因共同造成：
         1. 一个operatingItem必须有完整的数据，，不能根siftInfo一样只有其中几个属性，所以在初次定义时需要填写所有属性，
         这样就指定了其初定义类型，在传递参数时会起冲突，报错没有typeKey1,typeKey2等
         2.如果初始化时不指定值，那么ts默认添加一个undefined类型，这与原本的类型是不兼容的
         3. dialog中的数据必须有意义，所以不应该为其添加undefined类型，所以不能通过这种方式解决类型不兼容  -->
        <income-update-dialog v-if="budgetType===0" v-model:operating-item="(operatingItem as IncomeItemForInteraction)"
         @add-element="getSiftedData" v-model:is-show-update="isShowIncomeUpdate" v-model:dialog-type="dialogType"/>
        <expense-update-dialog v-if="budgetType===1" v-model:operating-item="(operatingItem as ExpenseItemForInteraction)" 
        @add-element="getSiftedData" v-model:is-show-update="isShowExpenseUpdate" v-model:dialog-type="dialogType"/>
        <delete-dialog v-model:is-show-delete="isShowDelete" :budgetType="budgetType" :budgetId="operatingItem.id" 
        @delete="getSiftedData"/>
    </div>
</template>

<script setup lang="ts">
import ExpenseFilterForm from '@/components/expenseFilterForm/index.vue'
import IncomeFilterForm from '@/components/incomeFilterForm/index.vue'
import ExpenseUpdateDialog from './expenseUpdateDialog/index.vue'
import IncomeUpdateDialog from './incomeUpdateDialog/index.vue'
import ModifyBudgetTable from './modifyBudgetTable/index.vue'
import DeleteDialog from './deleteDialog/index.vue'
import {ref,computed,watch,onMounted} from 'vue'
import { ExpenseItemForDisplay, ExpenseItemForInteraction, SiftedExpense } from '@/types/expense';
import { IncomeItemForDisplay, IncomeItemForInteraction, SiftedIncome } from '@/types/income';
import { getOnePageIncome } from '@/api/income'
import { getOnePageExpense } from '@/api/expense'
import useMemberStore from '@/store/modules/member'
import useFinanceStore from '@/store/modules/finance'
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
const DialogType = {
    ADDITION:0,
    MODIFY:1
}
let operatingItem = ref<ExpenseItemForInteraction|IncomeItemForInteraction>({
    id:0,
    member:null,
    typeKey:null,
    amount:0,
    time:'',
    description:''
})
let budgetData = ref<ExpenseItemForDisplay[]|IncomeItemForDisplay[]>([])
let dialogType = ref(DialogType.ADDITION)
let siftInfo = ref<SiftedExpense|SiftedIncome>({
    page:1,
    pageSize:10
})
let budgetType = ref(0)
let total = ref(0)
let isShowIncomeUpdate = ref(false)
let isShowExpenseUpdate = ref(false)
let isShowDelete = ref(false)
let filterForm = computed(()=>{
    return budgetType.value===0?IncomeFilterForm:ExpenseFilterForm
})
watch(budgetType,()=>{
    initSiftInfo()
    budgetData.value = []
    getSiftedData()
    
})
const openUpdateDialog = (init:Boolean)=>{
    dialogType.value=DialogType.ADDITION
    if(init)
        initOperatingItem()
    if(budgetType.value===0)
        isShowIncomeUpdate.value = true
    else isShowExpenseUpdate.value = true
}
const openModifyDialog = (row:IncomeItemForDisplay|ExpenseItemForDisplay)=>{
    const memberStore = useMemberStore()
    const financeStore = useFinanceStore()
    dialogType.value = DialogType.MODIFY
    if(budgetType.value===0){
       const {id,description,memberName,time,typeName,amount} = (row as IncomeItemForDisplay)
       let member = (memberStore.member.find((item)=>item.name==memberName)?.id as number)
       let typeKey = (financeStore.incomeType.find((item)=>item.typeName==typeName)?.id as number)
       operatingItem.value = {id,description,member,time,amount,typeKey}
       isShowIncomeUpdate.value = true
    }else{
        let {id,description,memberName,time,typeName1,typeName2,amount,beneficiary} = (row as ExpenseItemForDisplay)
        let member = (memberStore.member.find((item)=>item.name==memberName)?.id as number)
        let type1 = financeStore.expenseType.find(item=>item.typeName==typeName1) 
        let typeKey1 = (type1?.id as number)
        let typeKey2 = (type1?.secondList.find(item=>item.typeName==typeName2)?.id as number)
        beneficiary = (beneficiary as string)
        console.log(time);
        
        operatingItem.value = {id,description,member,time,amount,typeKey1,typeKey2,beneficiary}
        isShowExpenseUpdate.value = true
    }
    
}
const openDeleteDialog = (row:IncomeItemForDisplay|ExpenseItemForDisplay)=>{
    operatingItem.value.id = row.id
    isShowDelete.value = true
}
const initOperatingItem = ()=>{
    operatingItem.value = {
    id:0,
    member:null,
    typeKey:null,
    amount:0,
    time:'',
    description:''
}
}
const initSiftInfo = ()=>{
    siftInfo.value={
        page:1,
        pageSize:10
    }
}

const searchItems = async()=>{
    const keyWord = siftInfo.value.description
    initSiftInfo()
    siftInfo.value.description = keyWord
    if(budgetType.value===0){
        // 待补充
        const result = await getOnePageIncome(siftInfo.value)
        budgetData.value = result.data.records
        total.value = result.data.total
    }else {
        const result =await getOnePageExpense(siftInfo.value)
        budgetData.value = result.data.records
        total.value = result.data.total
    }
}
const getSiftedData = async()=>{
    if(budgetType.value===0){
        const result =await getOnePageIncome(siftInfo.value)
        total.value = result.data.total
        budgetData.value = result.data.records
        budgetData.value.forEach((item,index)=>{
            item.time = result.data.records[index].time.join('-')
        })
    }else {
        await getOnePageExpense(siftInfo.value).then(result=>{
            budgetData.value = result.data.records
            total.value = result.data.total
            budgetData.value.forEach((item,index)=>{
                item.time = result.data.records[index].time.join('-')
            })
        }).catch(error=>[
            console.dir(error)
        ])
    }
}

const postPic = async(option:any)=>{
    let formData = new FormData()
    formData.append(option.filename,option.file,option.file.name)
    const loading = ElLoading.service({
        lock:true,
        text:'上传图片中，请稍后...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const result = await axios({
        url:'http://localhost:8081/test',
        method:'post',
        data:formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
    })
    loading.close()
    
    setOperatingItem(result.data)
    openUpdateDialog(false)
}

const setOperatingItem = (data:any)=>{
    const financeStore = useFinanceStore()
    if(data.budgetType == null)
        ElMessage({
            type:'error',
            message:data.message
        })
    else if(data.budgetType == '收入'){
        initOperatingItem()
        budgetType.value = 0
        operatingItem.value.description = data.description
        operatingItem.value.amount = Number(data.amount)
        operatingItem.value.time = data.time
        operatingItem.value.member = (useMemberStore().member.find(item=>item.name=='家庭全员')?.id as number)
        let typeKey = financeStore.incomeType.find((item)=>item.typeName == data.typeName)?.id;
        (operatingItem.value as IncomeItemForInteraction).typeKey = (typeKey as number)
    }else if(data.budgetType == '支出'){
        console.log('本次添加被判断为支出')
        initOperatingItem()
        budgetType.value = 1
        operatingItem.value.description = data.description
        operatingItem.value.amount = Number(data.amount)
        operatingItem.value.time = data.time
        operatingItem.value.member = (useMemberStore().member.find(item=>item.name=='家庭全员')?.id as number)
        let type1 = null
        let typeKey2 = null
        // 不管typeName1是什么，typeName2都有可能被分类为其他，那么如果typeName2=其他，直接分类给其他类
        if(data.typeName2 == '其他'){
            type1 = financeStore.expenseType.find((item)=>item.typeName == '其他');

            typeKey2 = type1?.secondList.find(item=>item.typeName == '其他')?.id;
            console.log(type1,typeKey2)
        }else{
            type1 = financeStore.expenseType.find((item)=>item.typeName == data.typeName1);
            typeKey2 = type1?.secondList.find(item=>item.typeName == data.typeName2)?.id;
        }
        (operatingItem.value as ExpenseItemForInteraction).typeKey1 = (type1?.id as number);
        (operatingItem.value as ExpenseItemForInteraction).typeKey2 = (typeKey2 as number);
        // operatingItem.value.typeKey2 = typeKey2
        console.log(operatingItem.value, operatingItem.value.typeKey2);
        
        (operatingItem.value as ExpenseItemForInteraction).beneficiary = data.beneficiary
    }
}

onMounted(()=>{
    getSiftedData()
})
</script>

<style scoped>
.options {
    display: flex;
    margin: 10px 0;
}
</style>